//
//  FTowTime.swift
//  ThreadDriverText
//
//  Created by zhuxietong on 2021/3/8.
//  Copyright © 2021 Air. All rights reserved.
//

import Foundation
import Eelay
import DateTimePicker
import RxSwift

public enum TimePickerPlugin{
    case DateTimePicker
    case MEDateSelectionViewController
    case dialog
}


//
open class FTime:FField{
    
    public let textL = ASTextNode2()
    public let bt = ASButtonNode()
    public let indicator = ASImageNode()
    public weak var limitField:FTime? = nil
    public var limit:(min:Date?,max:Date?) = (Date(),Date().addingTimeInterval(60 * 60 * 24 * 7)){
        didSet{
            
            if let date = format.date{
                if let m = limit.min{
                    let r = date.timeSince(m)
//                    print("----IIIII99-===",r.0,date,m)
                    switch r.0 {
                    case .ealier:
                        
                        format.valueObject = ""
                        update(value: "", edit: .reply)
                    default:
                        break
                    }
                }
            }
            if let date = format.date{
                if let m = limit.max{
                    let r = date.timeSince(m)
//                    print("----IIIII88-===",r.0,date,m)

                    switch r.0 {
                    case .later:
                        format.valueObject = ""
                        update(value: "", edit: .reply)

                    default:
                        break
                    }
                }
            }
            updateDispaly()
        }
    }
    
    open override func didSetValue(value:Any) {
//        print("_sss____-s",value)
        format.valueObject = value
        if format.displayString.len > 0{
            textL.attributedText = format.displayString.ui.font(font: valueStyle.font).color(color: valueStyle.color).right.astring
        }else{
            textL.attributedText = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).right.astring
        }
    }
    open override func updateDispaly() {
        format.valueObject = value
        if format.displayString.len > 0{
            textL.attributedText = format.displayString.ui.font(font: valueStyle.font).color(color: valueStyle.color).right.astring
        }else{
            textL.attributedText = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).right.astring

        }
    }
    
    open override func didLayoutRules() {
        indicator.image = UIImage(_snamed: "indicator_more")
    }
    
    open override func addLayoutRules() {
        super.addLayoutRules()
        bt.addTarget(self, action: #selector(willToSelect), forControlEvents: .touchUpInside)
    }
    

    public var pickerType = TimePickerPlugin.dialog
    
    @objc func willToSelect(){
        if let f = limitField{
            if f.format.date == nil{
                f.placeholder.alert()
                return
            }
        }
        selectTime()
        
    }
    @objc open func selectTime() {
        switch pickerType {
        case .dialog:
            let dialog = FTimeDialog()
            dialog.time(timeF: self)
            dialog.show(at: mo.controller)
        case .DateTimePicker:
            selectWithDateTimePicker()
        case .MEDateSelectionViewController:
            break
//            selectWithMEDateSelectionViewController()
        }
    }
    

//    public override func updateDispaly() {
//        textField.textAlignment = .right
//        textField.attributedPlaceholder = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).right.astring
//        textField.ui.font(font: valueStyle.font).text(color: valueStyle.color).text(text: "\(format.displayString)")
//    }
    var format_:FForm.TimeFormat? = nil
    
    open lazy var format:FForm.TimeFormat = {
        let ps = initProps + self.defaultProps

        if let f = format_{
            return f
        }
        if let f = ps.format as? FForm.TimeFormat{
            format_ = f
            return f
        }
        let f = FForm.TimeFormat(displayF: .dispay("YYYY-MM-dd"), valueF: .second_stamp,mode: .day)
        format_ = f
        return f
    }()
   
    open override var defaultProps: [FProps]{
        get{
            let f = FForm.TimeFormat(displayF: .dispay("YYYY-MM-dd"), valueF: .second_stamp,mode: .day)
            return [.type(.select),.verify(.reg("\\S+")),.format(f)]
        }
    }
  

    
    open override func specGetter() -> _Spec {
        return _Spec.stack(["h|8",&-.center,_nowrap], childs: [
            textL[_grow(1),_shrink(1)],
            indicator["12",12],
        ]).addOver(bt.Spec)
    }
    
    @objc func selectWith(){

    }

}

open class FStartEndTime<F:FTime>:MoDisplayNode{
    
    public var initStartProps:[FProps] = []
    public var initEndProps:[FProps] = []
    public let startF:F
    public let endF:F
    
    public let bag = DisposeBag()
    public required init(start:[FProps],end:[FProps]) {
        self.initStartProps = start
        self.initEndProps = end
        self.startF = F.init(propsArray: self.initStartProps)
        self.endF = F.init(propsArray: self.initEndProps)
        super.init()
        endF.limitField = startF
        startF.status.subscribe(onNext:{
            [weak self] f in
            guard let `self` = self else{return}
            guard let date = self.startF.format.date else{return}
            self.endF.limit = (date,self.endF.limit.max)
        }).disposed(by: bag)
    }
    
    required public init() {
        fatalError("请使用 init(start:[FProps],end:[FProps]) 初始化")
    }
    
    open override func specGetter() -> _Spec {
        return _Spec.inset([], [20], child: .stack(["v|10",&-.stretch], childs: [
            startF.Spec,
            endF.Spec
        ]))
    }
    
    
    
}


//extension FTime:MEDateSelectionViewControllerDelegate{
//    public func dateSelectionViewController(_ vc: MEDateSelectionViewController!, didSelect aDate: Date!) {
//        if let date = aDate{
//            self.update(value: date, edit: .select)
//        }
//
//    }
//    func selectWithMEDateSelectionViewController() {
//        mo.controller?.view.endEditing(true)
//        guard let picker = MEDateSelectionViewController.dateSelection() else{return}
//
//
//        picker.delegate = self
//        picker.disableBouncingWhenShowing = true
//        picker.disableMotionEffects = true
//        picker.disableBlurEffects = true
//        picker.datePicker.minuteInterval = 5;
//
//        switch format.pickerMode {
//        case .day:
////            picker.isDatePickerOnly = true
//            picker.datePicker.datePickerMode = .date
//
//
//        case .hour:
//            picker.datePicker.datePickerMode = .dateAndTime
////            picker.includesMonth = true
//
//        default:
//            break
//        }
//
//        picker.hideNowButton = true;
//
////        if #available(iOS 13.4, *) {
////            picker?.datePicker.preferredDatePickerStyle = .wheels
////        } else {
////            // Fallback on earlier versions
////        }
////        if #available(iOS 13.4, *) {
////        } else {
////            // Fallback on earlier versions
////        }
//        //            picker?.datePicker.date = Date(timeIntervalSinceNow: 0)
//
//        picker.datePicker.date = format.date ?? Date()
//        picker.tintColor = ._tint
//        picker.show()
//    }
//
//}

extension FTime:DateTimePickerDelegate{
    func selectWithDateTimePicker() {
        let min = limit.min ?? Date()
        let max = limit.max ?? Date().addingTimeInterval(60 * 60 * 24 * 7)
        let picker = DateTimePicker.create(minimumDate: min, maximumDate: max)

        // customize your picker
//        picker.timeInterval = DateTimePicker.MinuteInterval.thirty
        picker.locale = Locale(identifier: "zh_Hans")

//        picker.todayButtonTitle = "Today"
//        picker.is12HourFormat = true
        picker.dateFormat = format.displayFormat.key


        switch format.pickerMode {
        case .day:
//            picker.isDatePickerOnly = true
            picker.includesMonth = true

        case .hour:
            picker.includesMonth = true

        default:
            break
        }
        picker.includesMonth = true

//        picker.includesMonth = false
//        picker.isTimePickerOnly = true
//        picker.includesSecond = false
//        picker.timeInterval = .five
        picker.highlightColor = ._tint

        picker.doneButtonTitle = "确定"
        picker.todayButtonTitle = "现在"
        picker.cancelButtonTitle = "取消"
        picker.doneBackgroundColor = ._tint
        picker.customFontSetting = DateTimePicker.CustomFontSetting(selectedDateLabelFont: .systemFont(ofSize: 20))
        if #available(iOS 13.0, *) {
            picker.normalColor = UIColor.secondarySystemGroupedBackground
            picker.darkColor = UIColor.label
            picker.contentViewBackgroundColor = UIColor.systemBackground
            picker.daysBackgroundColor = UIColor.groupTableViewBackground
            picker.titleBackgroundColor = UIColor.secondarySystemGroupedBackground
        } else {
            picker.normalColor = UIColor.white
            picker.darkColor = UIColor.black
            picker.contentViewBackgroundColor = UIColor.white
        }
        picker.completionHandler = {[weak self] date in
            guard let ws = self else {
                return
            }
            ws.update(value: date, edit: .select)

            self?.title = date[ws.format.displayFormat.key]
        }
        picker.delegate = self
        picker.tag = 1
        picker.show()
    }
    public func dateTimePicker(_ picker: DateTimePicker, didSelectDate: Date) {
//        update(value: didSelectDate, edit: .select)
    }


}

